package com.yuanfud.blog.service.impl;

import com.yuanfud.blog.service.FileService;
import com.yuanfud.common.exception.RestException;
import com.yuanfud.common.util.DateHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("FileService")
public class FileServiceImpl implements FileService {
    @Value("${file.uploadPath}")
    String uploadPath;

    @Override
    public boolean uploadFile(HttpServletRequest request,String attach) throws RestException, IOException {
        boolean result=false;
        String uploadPicturePath = uploadPath;
        String pathname = uploadPicturePath + "/"
                + DateHandler.dateToString(new Date(),"yyyyMMdd") + "/";
        File file = new File(pathname);
        if (!file.exists()) {
            file.mkdirs();
        }
        MultipartHttpServletRequest muti = (MultipartHttpServletRequest) request;

//        System.out.println(muti.getMultiFileMap().size());
//        System.out.println(pathname);

        MultiValueMap<String, MultipartFile> map = muti.getMultiFileMap();

        for (Map.Entry<String, List<MultipartFile>> entry : map.entrySet()) {

            List<MultipartFile> list = entry.getValue();
            for (MultipartFile multipartFile : list) {
                multipartFile.transferTo(new File(pathname +attach+ multipartFile.getOriginalFilename()));
                result=true;
            }
        }
        return result;
    }



    @Override
    public boolean delFile() throws RestException {

        return false;
    }
}
